﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.Companies.WebParts.RandomCompanyWebPart
{
    public partial class RandomCompanyWebPartUserControl : UserControl
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var repository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
            var companies = repository.GetApprovedCompanies();
            if (companies.Count == 0)
            {
                Visible = false;
                return;
            }

            var random = new Random(DateTime.Now.Millisecond);
            var index = random.Next(0, companies.Count - 1);
            var company = companies[index];

            companyDescription.InnerText = company.Description;
            if (companyDescription.InnerText.Length > 255)
                companyDescription.InnerText = companyDescription.InnerText.Substring(0, 255) + "...";
            companyTitleLink.InnerText = company.Title;
            companyTitleLink.HRef = company.DisplayUrl;
            companyLogoLink.HRef = companyTitleLink.HRef;

            companyLogo.Visible = false;
            SPFile logoFile = null; //web.Site.RootWeb.GetFile(logoUrl);

            if (logoFile != null)
                if (logoFile.Exists)
                {
                    //companyLogo.Src = logoUrl;
                    companyLogo.Visible = true;
                }
            companyLogoLink.Visible = companyLogo.Visible;
        }
    }
}
